package com.songwo.core.web.system;

import com.songwo.core.primary.dao.system.SysUserDao;
import com.songwo.core.primary.entity.system.SysUser;
import com.songwo.core.service.system.SysUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhongzheng
 */
@Log4j2
@RestController
@RequestMapping("/users")
public class SysUserController {
    /** 创建线程安全的map */
    private static Map<Long, SysUser> users = Collections.synchronizedMap(new HashMap<>());

    @Resource
    SysUserDao sysUserDao;

    @Resource
    SysUserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public List<SysUser> getUserList() {
        List<SysUser> sysUsers = userService.list();
        return sysUsers;
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
    @ApiImplicitParam(name = "sysUser", value = "用户详细实体user", required = true, dataType = "SysUser")
    public String postUser(@ModelAttribute SysUser sysUser) {
        sysUser = sysUserDao.save(sysUser);
//        System.out.println(JSON.toJSONString(sysUser));
        return "success";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public SysUser getUser(@PathVariable Long id) {
        SysUser sysUser = sysUserDao.findSysUserById(id);
        return sysUser;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String putUser(@PathVariable Long id, @ModelAttribute SysUser sysUser) {
        // 处理"/users/{id}"的PUT请求，用来更新User信息
        SysUser u = users.get(id);
        u.setName(sysUser.getName());
        u.setAge(sysUser.getAge());
        users.put(id, u);
        return "success";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        // 处理"/users/{id}"的DELETE请求，用来删除User
        users.remove(id);
        return "success";
    }
}
